package controllers;

import java.util.Date;
import java.util.List;

import controllers.Secure.Security;

import models.BlogEntry;
import models.DeletedBlogEntry;
import models.User;
import play.mvc.Controller;
import play.mvc.With;

@With(Secure.class)
public class Admin extends Controller {
	
	public static void index() {
		render();
	}
	
	public static void blogs() {
		List<BlogEntry> entrys = null;
		Integer total = null;
		
		total = BlogEntry.all().count();
		entrys = BlogEntry.all().fetch();
		
		render(total, entrys);
	}
	
	public static void editBlog(Long id) {
		if(id == null) {
			render();
		} else {
			BlogEntry entry = null;
			entry = BlogEntry.all().filter("id", id).get();
			render(entry);
		}
	}
	
	public static void saveBlog(Long id, String title, String tags, String content) {
		BlogEntry entry = null;
		Date cur = new Date();
		if(id == null) {
			entry = new BlogEntry();
			entry.createTime = cur;			
		} else {
			entry = BlogEntry.all().filter("id", id).get();
		}
		entry.title = title;
		entry.content = content;
		entry.lastModifyTime = cur;
		
		String authorName = Security.connected();
		User author = User.all().filter("loginName", authorName).get();
		entry.authorId = author.id;	
		
		if(entry.id == null) {
			entry.insert();
		} else {
			entry.update();
		}
		
		entry.saveTags(tags);
		
		editBlog(entry.id);
	}
	
	public static void delBlog(Long id) {
		BlogEntry entry = null;
		entry = BlogEntry.all().filter("id", id).get();
		DeletedBlogEntry delEntry = new DeletedBlogEntry(entry);
		delEntry.insert();
		entry.delete();
		
		blogs();
	}
	
}
